//
//  XZMessageViewController.m
//  XZ_WeChat
//
//  Created by 郭现壮 on 16/9/27.
//  Copyright © 2016年 gxz. All rights reserved.
//

#import "XZMessageViewController.h"
#import "XZGroupSearchController.h"
#import "XZMessageCell.h"
#import "XZChatViewController.h"


@interface XZMessageViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchResultsUpdating,UISearchBarDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) UISearchController *searchController;
//@property (nonatomic,assign) BOOL isVisable;

@end

@implementation XZMessageViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
//    self.isVisable = YES;
    [self loadDataSource:nil];

}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
//    self.isVisable = NO;

    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
    
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(loadDataSource:) name:LOGIN_SUCCESS object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(SRWebSocketDidReceiveMsg:) name:kWebSocketdidReceiveMessageNote object:nil];
    
}


-(void)SRWebSocketDidReceiveMsg:(NSNotification*)note
{
    
    NSDictionary *result = [NSDictionary dictionaryWithJsonString:note.object];
    if ([result[@"code"] intValue]==1) {
        
        ICMessage *message = [ICMessage mj_objectWithKeyValues:result[@"data"]];
           
        NSMutableArray *arrar = [NSMutableArray array];
                   
           for (XZGroup *group in self.dataArray) {
                             
               [arrar addObject:group.gId];
                             
             }
                 
        
        if ([arrar containsObject:message.from]) {
            for (XZGroup*group in self.dataArray) {
                       if ([group.gId intValue]==[message.from intValue]) {
                           group.unReadCount++;
                           group.lastMsgString = message.content;
                           
                       }
                       
                   }
                   
                   [self.tableView reloadData];
        }else{
            
            [self loadDataSource:nil];
        }
        
        
        
       
        
                    
                    
     }
    
}

- (void)setupUI
{
    self.view.backgroundColor = XZRGB(0xf4f1f1);
    self.tableView.backgroundColor = XZRGB(0xf4f1f1);
    XZGroupSearchController *searchVC    = [[XZGroupSearchController alloc] init];
//    searchVC.delegate                    = self;
    UISearchController *searchController = [[UISearchController alloc] initWithSearchResultsController:searchVC];
    [searchController.searchBar sizeToFit];
    self.tableView.tableHeaderView = searchController.searchBar;
    _searchController              = searchController;
    [searchController.searchBar setBarTintColor:BACKGROUNDCOLOR];
    [searchController.searchBar.layer setBorderWidth:0.5f];
    [searchController.searchBar.layer setBorderColor:BACKGROUNDCOLOR.CGColor];
    searchController.dimsBackgroundDuringPresentation = YES;
    self.definesPresentationContext = YES;
    searchController.view.backgroundColor = [UIColor whiteColor];
    searchController.hidesNavigationBarDuringPresentation = YES;
    searchController.searchResultsUpdater = self;
    searchVC.definesPresentationContext = YES;
    searchController.searchBar.delegate = self;
    self.tableView.frame  = CGRectMake(0,0, self.view.width, APP_Frame_Height-TabbarHeight);
    
    WEAKSELF
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf loadDataSource:nil];
    }];
}

- (void)loadDataSource:(NSNotification*)notifi
{
    
    
   
    //页面不显示，就不调用了
//    if (!_isVisable) return;
    
    if (notifi) {
        [self.dataArray removeAllObjects];
        
    }
    

    
    
    [LZDSocketTool loadSessionListUserId:[[NSUserDefaults standardUserDefaults]objectForKey:USER_ID] Result:^(NSArray<XZGroup *> * _Nonnull list) {
        [self.tableView.mj_header endRefreshing];

        if (list.count!=0) {
            if (self.dataArray.count==0) {
             [self.dataArray addObjectsFromArray:list];
                
            }
            
            NSMutableArray *arrar = [NSMutableArray array];
            
            for (XZGroup *group in self.dataArray) {
                              
                [arrar addObject:group.gId];
                              
              }
            
            NSMutableArray *re_arrar = [NSMutableArray arrayWithArray:list];

            for (XZGroup *re_group in list) {
                
                if ([arrar containsObject:re_group.gId]) {
                    [re_arrar removeObject:re_group];
                }
                
               
               
                
            }
            for (XZGroup *re_group in re_arrar) {
                re_group.unReadCount++;
                [self.dataArray insertObject:re_group atIndex:0];

                            }
            

            
           
            
//               [self.dataArray addObjectsFromArray:list];
        }
      
        [self.tableView reloadData];

    }];
    
  
}



#pragma mark - tableViewDelegate

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    XZMessageCell *cell = [XZMessageCell cellWithTableView:tableView];
    if (indexPath.row == self.dataArray.count - 1) {
        [cell setBottomLineStyle:CellLineStyleNone];
    }
    else {
        [cell setBottomLineStyle:CellLineStyleDefault];
    }
    cell.group = self.dataArray[indexPath.row];
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 67.0;
}

- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *topTitle ,*readTitle;
    XZGroup *group  = self.dataArray[indexPath.row];
    topTitle  = group.isTop ? @"取消置顶" : @"置顶";
    readTitle = group.unReadCount ? @"标为已读" : @"标为未读";
    //设置删除按钮
    UITableViewRowAction * deleteRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
//        [self deleteLocalGroup:indexPath];
    }];
    //置顶
    UITableViewRowAction * topRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:topTitle handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
//        [self setTopCellWithIndexPath:indexPath currentTop:group.isTop];
    }];
    //标记已读
    UITableViewRowAction * collectRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:readTitle handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
//        [self markerReadWithIndexPath:indexPath currentUnReadCount:group.unReadCount];
    }];
    collectRowAction.backgroundColor = [UIColor grayColor];
    topRowAction.backgroundColor     = [UIColor orangeColor];
    return  @[deleteRowAction,topRowAction,collectRowAction];
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return NO;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    XZGroup *group               = self.dataArray[indexPath.row];
    group.unReadCount = 0;
    XZChatViewController *chatVc = [[XZChatViewController alloc] init];
    chatVc.group                 = group;
    [self.navigationController pushViewController:chatVc animated:YES];
}



-(void)updateSearchResultsForSearchController:(UISearchController *)searchController{
    
    NSString *keyword = searchController.searchBar.text;
    
    LxDBAnyVar(keyword);
    
}

-(void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
    
    LxDBAnyVar(searchBar.text);
    NSString * userid = [[NSUserDefaults standardUserDefaults] objectForKey:USER_ID];
    if (userid == nil || userid.length==0) {
        return;
    }
    
    [LZDSocketTool SearchUserWithParamer:@{@"user_id":[[NSUserDefaults standardUserDefaults] objectForKey:USER_ID],@"keyword":searchBar.text} Result:^(NSArray<XZGroup *> * _Nonnull userList) {
        XZGroupSearchController *searchVC = (XZGroupSearchController*)self.searchController.searchResultsController;
        
        searchVC.data_A =  userList;
        [searchVC.tableView reloadData];
        
        
    }];
    
    
    

    
}




#pragma mark - setter and getter

- (UITableView *)tableView
{
    if (nil == _tableView) {
        UITableView * tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        tableView.delegate = self;
        tableView.dataSource = self;
        [self.view addSubview:tableView];
        tableView.showsVerticalScrollIndicator = NO;
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView = tableView;
    }
    return _tableView;
}

- (NSMutableArray *)dataArray
{
    if (nil == _dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return  _dataArray;
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:LOGIN_SUCCESS object:nil];
}

@end
